<template>
  <el-dialog v-model="drawer" @close="close" :append-to-body="true" width="1000px" title="客户阶段设置">
    <el-button size="small" type="primary" style="margin-bottom: 5px" @click="openForm(null)">添加</el-button>
    <el-table :data="stageList" size="small" stripe border :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}">
<!--      <el-table-column type="selection" width="50" fixed="left"/>-->
      <el-table-column label="名称" prop="name" width="130"/>
      <el-table-column label="位置" width="100">
        <template v-slot="{row}">{{ row.type == 0 ? '主干' : (row.type == 1 ? '完成分支' : '异常分支') }}</template>
      </el-table-column>
      <el-table-column label="排序号" prop="sort" width="100"/>
      <el-table-column label="备注" prop="remark"/>
      <el-table-column label="操作" width="130">
        <template v-slot="{row}">
          <el-button size="small" type="warning" :icon="View" text @click="editVisible(row)">{{ row.visible ? '隐藏' : '显示' }}</el-button>
          <el-button size="small" type="primary" :icon="Edit" text @click="openForm(row)">编辑</el-button>
          <el-button size="small" type="danger" :icon="Delete" v-if="row['permitDel'] == 1" text @click="deleteStage(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑阶段 -->
    <el-dialog v-model="formVisible" @close="formClose" :append-to-body="true" width="500px" title="客户阶段">
      <el-form :model="form" :rules="rules" size="small" label-width="100px" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请填写名称" clearable maxlength="8"/>
        </el-form-item>
        <el-form-item label="是否可见" prop="visible">
          <el-switch v-model="form.visible" active-text="可见" inactive-text="不可见" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="位置" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">主干</el-radio>
            <el-radio :label="1">完成分支</el-radio>
            <el-radio :label="2">异常分支</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" :min="-99999" :max="99999" :controls="false"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="small" @click="formVisible = false">关闭</el-button>
        <el-button size="small" type="primary" :loading="submitLoading" @click="submitStage(formRef)">提交</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button size="small" type="primary" @click="drawer = false">确定</el-button>
<!--      <el-button size="small" type="primary" :loading="submitLoading" @click="submitData">提交</el-button>-->
    </template>
  </el-dialog>
</template>
<script>
import {computed, reactive, toRefs, ref} from 'vue'
import {Edit, Delete, View} from '@element-plus/icons-vue'
import stageApi from '/@/api/ums/customer/opportunityStage'
import {ElMessage, ElMessageBox} from 'element-plus'

export default {
  name: 'StageSetting',
  props: {
    dialogDrawer: {
      type: Boolean,
      default: false
    }
  },
  emits: ['callback', 'update:dialogDrawer'],
  setup(props, context) {
    const {dialogDrawer} = toRefs(props)
    const formRef = ref()
    const state = reactive({
      form: {
        id: null,
        name: null,
        visible: 1,
        type: 0,  // 0主干, 1完成分支, 2异常分支
        sort: 0,
        remark: null
      },
      rules: {
        name: {required: true, message: '请填写阶段名称', trigger: 'blur'}
      },
      formVisible: false,
      stageList: [],
      selectedList: [],   // 选中需要显示的阶段
      submitLoading: false
    })

    let drawer = computed({
      get: () => {
        if (dialogDrawer.value) {
          getData()
        }
        return dialogDrawer.value
      },
      set: (val) => context.emit('update:dialogDrawer', val)
    })

    const getData = () => stageApi.getList().then(res => state.stageList = res.data || []).catch(e => console.log(e))
    const close = () => {
      context.emit('callback')
      context.emit('update:dialogDrawer', false)
    }
    /**
     * 提交添加/编辑的阶段数据
     */
    const submitStage = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return
        }
        let res
        state.submitLoading = true
        try {
          if (state.form.id) {
            res = await stageApi.edit(state.form)
          } else {
            res = await stageApi.add(state.form)
          }
          state.submitLoading = false
          if (res.data) {
            getData()
            state.formVisible = false
            ElMessage.success('提交成功！')
          }
        } catch (e) {
          console.log(e)
        }
      })
    }
    /**
     * 提交选中显示的阶段列表, 关闭阶段设置框
     */
    const submitData = () => {
      if (!state.selectedList && state.selectedList.length == 0) {
        return ElMessage.warning('请选择要显示的跟进阶段')
      }
      state.submitLoading = true
      stageApi.saveDisplay(state.selectedList).then(res => {
        state.submitLoading = false
        if (res.data) {
          ElMessage.success('提交成功！')
          context.emit('update:dialogDrawer', false)
        }
      }).catch(e => {
        console.log(e)
        state.submitLoading = false
      })
    }
    const openForm = (stage) => {
      if (stage && stage.id) {
        state.form = JSON.parse(JSON.stringify(stage))
      } else {
        resetForm()
      }
      state.formVisible = true
    }
    const deleteStage = (stage) => {
      ElMessageBox.confirm('确定删除 ' + stage.name + ' ？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        stageApi.remove(stage).then(res => {
          if (res.data) {
            getData()
            ElMessage.success('删除成功！')
          }
        })
      }).catch(() => {
      })
    }
    const formClose = () => {
      resetForm()
      state.formVisible = false
    }
    const resetForm = () => {
      state.form = {
        id: null,
        name: null,
        visible: 1,
        type: 0,  // 0主干, 1完成分支, 2异常分支
        sort: 0,
        remark: null
      }
    }
    const selection = (selections) => state.selectedList = selections
    const editVisible = (item) => {
      let data = JSON.parse(JSON.stringify(item))
      data.visible = data.visible ? 0 : 1
      stageApi.modifyVisible(data).then(res => {
        if (res.data) {
          item.visible = data.visible
          ElMessage.success('修改成功！')
        }
      }).catch(e => console.log(e))
    }

    return {
      Edit,
      close,
      drawer,
      Delete,
      View,
      formRef,
      openForm,
      selection,
      formClose,
      submitData,
      submitStage,
      deleteStage,
      editVisible,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped lang="scss">
</style>
